import config
import pymssql


def query_db(table_name):
    conn = pymssql.connect(config.mssql_ip, config.mssql_user, config.mssql_pass, config.mssql_db, port=config.mssql_port)
    cursor = conn.cursor()
    sql = f'SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH  FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_CATALOG=\'{config.mssql_db}\' and TABLE_SCHEMA=\'dbo\' and TABLE_NAME=\'' + table_name + '\''
    cursor.execute(
        sql
        )
    data = cursor.fetchall()
    cursor.close()
    conn.close()
    # print( data)
    return data


def write_to_file(dir_path, table_name):
    data_list = query_db(table_name)
    output = open(dir_path, 'w+')
    for col_name, col_type, col_len in data_list:
        w_line = ''
        if (col_len is None):
            w_line = col_name + " " + col_type
        else:
            w_line = col_name + " " + col_type + "(" + str(col_len) + ")"
        output.write(w_line + "\n")
        # print(data_list[i])
    output.close()


query_db("cust")
